<template>
  <div class="container">
    <button @click="sendMessage">发送消息</button>
    <div v-html="responseContent"></div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const responseContent = ref('') // 用于存储和展示来自模型的响应
const prop = '给我介绍下浙江华咨结构设计事务有限公司'
async function sendMessage() {
  const message = { role: 'user', content: prop }
  const responseContentTemp = [] // 临时存储响应部分

  try {
    // const response = await fetch('http://127.0.0.1:11434/api/chat', {
    const response = await fetch('http://192.168.1.198:11434/api/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        model: 'deepseek-r1:7b',
        messages: [message],
        stream: true,
      }),
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      const chunk = decoder.decode(value, { stream: true })
      const lines = chunk.split('\n').filter((line) => line.trim())

      for (const line of lines) {
        try {
          const part = JSON.parse(line)
          if (part.message && part.message.content) {
            responseContentTemp.push(part.message.content)
          }
        } catch (error) {
          console.error('Error parsing JSON:', error)
        }
      }

      // 实时更新DOM
      responseContent.value = responseContentTemp.join('')
    }
  } catch (error) {
    console.error('Error during chat:', error)
  }
}
</script>

<style scoped>
/* 根据需要添加样式 */
.container {
  padding: 20px;
}
</style>
